package com.meida.student.app.user;

import com.alibaba.fastjson.JSON;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.handler.AppProxyHandler;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.module.user.client.entity.AppSchool;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppSchoolService;
import com.meida.module.user.provider.service.AppUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyAppPropxy implements AppProxyHandler {
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private AppSchoolService appSchoolService;

    @Override
    public ResultBody validate(String url, EntityMap params) {
        log.info("MyAppPropxy:参数" + JSON.toJSONString(params));
        if (url.indexOf("addToWatchList") != -1) {
            Long userId = OpenHelper.getUserId();
            AppUser appUser = appUserService.getUserById(userId);
            Integer busNum = FlymeUtils.getInteger(appUser.getBusNum(), 0);
            params.put("userId", userId);
            params.put("busNum", busNum);
            if (busNum == 0) {
                EntityMap result = new EntityMap();
                result.put("result", "noLocation");
                return ResultBody.failed(2002, "空位不足");
            }
        }
        if (url.contains("getCourseNames")) {
            Long userId = OpenHelper.getUserId();
            AppUser appUser = appUserService.getUserById(userId);
            AppSchool appSchool = appSchoolService.getById(appUser.getSchoolId());
            if (FlymeUtils.isEmpty(appSchool)) {
                return ResultBody.failed("未绑定学校");
            }
            Integer isOpen = FlymeUtils.getInteger(appSchool.getIsOpen(), 0);
            if (isOpen == 0) {
                return ResultBody.failed("您的学校暂未开通此功能，敬请期待！");
            }
        }
        return ResultBody.ok();
    }

    @Override
    public void complete(String url, EntityMap params) {
        //扣减数量
        if (url.indexOf("addToWatchList") != -1) {
            Long userId = params.getLong("userId");
            Integer busNum = params.getInt("busNum") - 1;
            if (busNum < 0) {
                busNum = 0;
            }
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.set(true, "busNum", busNum);
            cu.eq(true, "userId", userId);
            appUserService.update(cu);
        }
    }
}
